package com.longjianghuasheng.logistics.util

import android.text.TextUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.longjianghuasheng.logistics.business.home.ServiceType
import com.longjianghuasheng.logistics.data.model.bean.UserInfo
import com.tencent.mmkv.MMKV

object CacheUtil {


    private val kv = MMKV.mmkvWithID("app")


    fun getFilePath(key: String) = kv.decodeString(key)

    fun setFilePath(key:String,path:String) = kv.encode(key,path)



    var service_type: ServiceType
        get() = Gson().fromJson(kv.decodeString("service_type"), ServiceType::class.java)
        set(value) {

            kv.encode("service_type", Gson().toJson(value))
        }

    //    const val token: String = "b3cd95a7886f6807e6e274a8ebe3cfd2"
    var token: String
        get() = kv.decodeString("token") ?: ""
        set(value) {
            kv.encode("token", value)
        }


    var serverType: String
        get() = kv.decodeString("type") ?: ""
        set(value) {
            kv.encode("type", value)
        }


    /**
     * 获取保存的账户信息
     */
    fun getUser(): UserInfo? {
        val userStr = kv.decodeString("user")
        return if (TextUtils.isEmpty(userStr)) {
            null
        } else {
            Gson().fromJson(userStr, UserInfo::class.java)
        }
    }

    /**
     * 设置账户信息
     */
    fun setUser(userResponse: UserInfo?) {
        if (userResponse == null) {
            kv.encode("user", "")
            isLogin = false
        } else {
            kv.encode("user", Gson().toJson(userResponse))
            isLogin = true
        }

    }

    /**
     * 是否已经登录
     */
    var isLogin: Boolean
        get() = kv.decodeBool("login", false)
        set(value) {
            kv.encode("login", value)
        }


    /**
     * 是否是第一次登陆
     */
    var isFirst: Boolean
        get() = kv.decodeBool("first", true)
        set(value) {
            kv.encode("first", value)

        }


    /**
     * 是否是司机
     */
    var isDriver: Boolean
        get() = kv.decodeBool("isDriver", false)
        set(value) {
            kv.encode("isDriver", value)
        }

    /**
     * 首页是否开启获取指定文章
     */
    fun isNeedTop(): Boolean {
        return kv.decodeBool("top", true)
    }

    /**
     * 设置首页是否开启获取指定文章
     */
    fun setIsNeedTop(isNeedTop: Boolean): Boolean {
        return kv.encode("top", isNeedTop)
    }

    /**
     * 获取搜索历史缓存数据
     */
    fun getSearchHistoryData(): ArrayList<String> {
        val kv = MMKV.mmkvWithID("cache")
        val searchCacheStr = kv.decodeString("history")
        if (!TextUtils.isEmpty(searchCacheStr)) {
            return Gson().fromJson(searchCacheStr, object : TypeToken<ArrayList<String>>() {}.type)
        }
        return arrayListOf()
    }

    fun setSearchHistoryData(searchResponseStr: String) {
        val kv = MMKV.mmkvWithID("cache")
        kv.encode("history", searchResponseStr)
    }
}